package com.cash.app.custom

import android.content.Context
import android.util.AttributeSet
import android.widget.ImageView
import android.widget.RadioGroup
import com.cash.app.R

class IconRatingBar(context: Context, attrs: AttributeSet) : RadioGroup(context, attrs) {
    private var starCount = 5
    private var rating = 5f
    private val starIcons = mutableListOf<ImageView>()

    init {
        orientation = HORIZONTAL
        setupStars()
    }

    private fun setupStars() {
        removeAllViews()
        starIcons.clear()

        for (i in 0 until starCount) {
            val star = createStarIcon()
            star.setOnClickListener { setRating(i + 1f) }
            addView(star)
            starIcons.add(star)
        }
        updateStars()
    }

    private fun createStarIcon(): ImageView {
        return ImageView(context).apply {
            layoutParams = LayoutParams(
                resources.getDimensionPixelSize(R.dimen.star_size),
                resources.getDimensionPixelSize(R.dimen.star_size)
            ).apply {
                marginEnd = resources.getDimensionPixelSize(R.dimen.star_item)
            }
            setImageResource(R.drawable.custom_rating_bar)
        }
    }

    fun setRating(value: Float) {
        rating = value.coerceIn(0f, starCount.toFloat())
        updateStars()
    }

    fun getRating(): Int {
        rating = rating.coerceIn(0f, starCount.toFloat())
        return rating.toInt()
    }

    private fun updateStars() {
        starIcons.forEachIndexed { index, star ->
            val drawable = when {
                rating >= index + 1 -> R.mipmap.love_red
                rating > index -> R.mipmap.love_grew
                else -> R.mipmap.love_grew
            }
            star.setImageResource(drawable)
        }
    }
}